checkLogin()
renderUsername()
logout()

// 渲染学生列表
async function render() {
    const res = await axios.get('/students')
    // console.log(res.data)
    const res1 = res.data.map((item,index) => {
        return `
        <tr>
            <td>${item.name}</td>
            <td>${item.age}</td>
            <td>${item.gender === 0 ? '男' : '女'}</td>
            <td>${item.group}</td>
            <td>${item.hope_salary}</td>
            <td>${item.salary}</td>
            <td>${item.province} ${item.city} ${item.area}</td>
            <td data-id="${item.id}">
                <a href="javascript:;" class="text-success mr-3"><i class="bi bi-pen"></i></a>
                <a href="javascript:;" class="text-danger"><i class="bi bi-trash"></i></a>
            </td>
        </tr>
    `
    }).join('')
    document.querySelector('.list').innerHTML = res1
    document.querySelector('.total').innerHTML = res.data.length
}
render()

// 删除和编辑
document.querySelector('.list').addEventListener('click',function(e) {
    if (e.target.classList.contains('bi-trash')) {
        delStudent(e.target.parentNode.parentNode.dataset.id)
    }
    if (e.target.classList.contains('bi-pen')) {
        editStudent(e.target.parentNode.parentNode.dataset.id)
        modalEl.dataset.id=e.target.parentNode.parentNode.dataset.id
    }
})

// 删除学员
async function delStudent(id) {
    const con = confirm('确定要删除吗？')
    if (con) {
        await axios.delete(`/students/${id}`)
        showToast('删除成功')
        render()
    }
}


async function editStudent(id){
      modal.show()
      document.querySelector('.modal-title').innerHTML=`修改学员`
     const res=await axios.get(`/students/${id}`)
    //  console.log(res)
     const arr=['name','age','hope_salary','salary','group']
     arr.forEach((item)=>{
      document.querySelector(`[name=${item}]`).value=res.data[item]
     })
    
     const {gender} =res.data
    
     const cks=document.querySelectorAll('[name=gender]')
     cks[gender].checked=true
    
     const {province,city,area} = res.data
     document.querySelector('[name=province]').value = province
     const cityRes =await axios.get('/api/city',{
        params:{pname:province}
     })
     document.querySelector('[name=city]').innerHTML = `<option value="">--城市--</option>` + cityRes.list.map(item=>{
        return `<option value="${item}">--${item}--</option>`
     }).join('')
     document.querySelector('[name=city]').value = city
     
     const areaRes =await axios.get('/api/area',{
        params:{pname:province,cname:city}
     })
     document.querySelector('[name=area]').innerHTML = `<option value="">--地区--</option>` + areaRes.list.map(item=>{
        return `<option value="${item}">--${item}--</option>`
     }).join('')
     document.querySelector('[name=area]').value = area
    }

const modalEl = document.querySelector('#modal')
const modal = new bootstrap.Modal(modalEl)

document.querySelector('#openModal').addEventListener('click',function() {
    modal.show()
    document.querySelector('.modal-title').innerHTML = '添加学员'
})



// 获取省份
async function initSelete () {
    const res1 = await axios({
        url:'https://hmajax.itheima.net/api/province'
    })
    // console.log(res1.list)
    document.querySelector('[name="province"]').innerHTML = '<option value="">省份</option>' + res1.list.map(item=>{
        return `<option value="${item}">${item}</option>`
    }).join('')

    // 获取城市
    let pname = ''
    document.querySelector('[name="province"]').addEventListener('change',async function() {
        pname = this.value
        const res2 = await axios({
            url:'https://hmajax.itheima.net/api/city',
            params:{
                pname
            }
        })
        // console.log(res2.list)
        document.querySelector('[name="city"]').innerHTML = '<option value="">城市</option>' + res2.list.map(item=>{
            return `<option value="${item}">${item}</option>`
        }).join('')
        document.querySelector('[name="area"]').innerHTML = '<option value="">区县</option>'
    })

    // 获取区县
    document.querySelector('[name="city"]').addEventListener('change',async function() {
        cname = this.value
        const res3 = await axios({
            url:'https://hmajax.itheima.net/api/area',
            params:{
                pname,
                cname
            }
        })
        // console.log(res3.list)
        document.querySelector('[name="area"]').innerHTML = '<option value="">区县</option>' + res3.list.map(item=>{
            return `<option value="${item}">${item}</option>`
        }).join('')
    })
}

initSelete()

document.querySelector('#submit').addEventListener('click',function() {
    // addStudent()
    if (modalEl.dataset.id) {
        // console.log('这是发请求的代码')
        saveStudent()
    } else {
        addStudent()
    }
})

async function saveStudent() {
    const data = serialize(form,{hash:true,empty:true})
    data.age = +data.age
    data.gender = +data.gender
    data.group = +data.group
    data.hope_salary = +data.hope_salary
    data.salary = +data.salary
    const res = await axios.put(`/students/${modalEl.dataset.id}`,data)
    showToast(res.message)
    render()
    modal.hide()
}


const form = document.querySelector('#form')
// 添加学员
async function addStudent() {
    const data = serialize(form,{hash:true,empty:true})
    data.age = +data.age
    data.gender = +data.gender
    data.group = +data.group
    data.hope_salary = +data.hope_salary
    data.salary = +data.salary
    // console.log(data)
    const res = await axios.post('/students',data)
    showToast(res.message)
    render()
    modal.hide()
    form.reset()
}
